import { createAxiosInstance } from '@x-tech/fe-puma-lib-http/dist/index';
import { AxiosInstance } from 'axios';
import { store } from '@/store';
import { Toast } from 'vant';
import type { ToastWrapperInstance } from 'vant/es/toast/types';

Toast.allowMultiple();
function getToken(): string {
    return store.state.shadow.token;
}

function notice(): string {
    return '';
}
interface ConfigModel {
    [key: string]: any
}

let toastLoading: ToastWrapperInstance;

export function showLoading() {
    if (toastLoading) {
        toastLoading?.clear();
    }
    toastLoading = Toast.loading({
        message: '加载中....',
        forbidClick: true,
        duration: 0
    });
}

export function clearLoading() {
    toastLoading?.clear();
}

// eslint-disable-next-line
// let toastLoading: any = null;
// eslint-disable-next-line
let needLoadingRequestCount = 0;
function create$http(): AxiosInstance {
    const args = {
        config: {
            baseURL: window.XCConfig.VUE_APP_API_URL,
            timeout: 60000,
        },
        successCodes: [0, '0', '000'],
        isBasic: true,
        getToken,
        notice,
    };

    return createAxiosInstance(args);
}

const $http = create$http();
$http.interceptors.request.use(
    (config: ConfigModel) => {
        // if(!toastLoading){
        //     // eslint-disable-next-line
        //     needLoadingRequestCount++;
        //     toastLoading = Toast.loading({
        //         message: '加载中....',
        //         forbidClick: true,
        //         duration: 0, // 持续展示 toast
        //     });
        // }
        return config;
    },
    (err) => {
        console.error(err);
        return Promise.reject(err);
    }
);
$http.interceptors.response.use(
    res => {
        // if (toastLoading) {
        //     needLoadingRequestCount--;
        //     if (needLoadingRequestCount <= 0) {
        //         Toast.clear();
        //         // eslint-disable-next-line
        //         toastLoading.clear();
        //         toastLoading = null;
        //     }
        // }
        return res;
    },
    (err: ConfigModel) => {
        console.error(err);
        // needLoadingRequestCount=0;
        // Toast.clear();
        // if(toastLoading){
        //     // eslint-disable-next-line
        //     toastLoading.clear();
        //     toastLoading = null;
        // }

        const message = (err.msg || err.message || '返回错误！') as unknown as string;
        Toast.fail({
            duration: 1500,
            forbidClick: true,
            closeOnClick: true,
            message: message,
        });
        clearLoading();
        return Promise.reject(err);
    }
);

export { $http };
